package weaver.jobs.zhlx.duss.cron;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;

import java.util.concurrent.TimeUnit;

/**
 * @Title: ecology
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2023-08-29
 * @Description: 根据人员离职记录表中
 * * 权限自动转移项：待办、流程节点操作者、角色
 * * 权限转移时间：若拟离职日期>归档日期，即流程离职日期进行权限转移；
 * @ModifyLog:
 **/

public class WeaPermissTransCron extends BaseCronJob {

    @Override
    public void execute() {
        try {
            BaseBean baseBean = new BaseBean();
            String currentDate = DateUtil.getCurrentDate();
            baseBean.writeLog(">>>>>WeaPermissTransCron>>>>>currentDate=" + currentDate);
            RecordSet rs = new RecordSet();
            rs.executeQuery("select lzlc,lzr,gzjjr,jszysl,lcjdczzzysl,dbsyzysl from uf_rylzjlb where lzrq>lcgdrq and (qxsfgx is null or qxsfgx=1)");
            while (rs.next()) {
                String lzlc = Util.null2String(rs.getString("lzlc"));
                String lzr = Util.null2String(rs.getString("lzr"));
                String gzjjr = Util.null2String(rs.getString("gzjjr"));
                String jszysl = Util.null2String(rs.getString("jszysl"));
                String lcjdczzzysl = Util.null2String(rs.getString("lcjdczzzysl"));
                String dbsyzysl = Util.null2String(rs.getString("dbsyzysl"));
                if (!("0".equals(jszysl) && "0".equals(lcjdczzzysl) && "0".equals(dbsyzysl))) {
                    JSONObject params = new JSONObject();
                    params.put("fromid", lzr);
                    params.put("toid", gzjjr);
                    params.put("transferType", "resource");
                    params.put("authorityTag", "transfer");
                    params.put("submitJson", "");
                    params.put("T122All", 1);
                    params.put("T122AllNum", jszysl);
                    params.put("T131All", 1);
                    params.put("T131AllNum", lcjdczzzysl);
                    params.put("T133IdStr",getRequestidStr(lzr));
                    JSONObject tokenJson = getApplytoken();
                    JSONObject toDataJson = tokenJson.getJSONObject("data");
                    String token = toDataJson.getString("token");
                    baseBean.writeLog(">>>>>WeaPermissTransCron>>>>>params=" + params);
                    JSONObject resultJson = sendPostOKHttpRequest(params, token);
                    baseBean.writeLog(">>>>>WeaPermissTransCron>>>>>resultJson=" + resultJson);
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    String status = Util.null2String(dataJson.getString("status"));
                    String message = Util.null2String(dataJson.getString("message"));
                    String qxsfgx = !"1".equals(status)?"1":"0";
                    rs.executeUpdate("update uf_rylzjlb set gxjg=?,qxsfgx=? where lzlc=?", message, qxsfgx, lzlc);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 发送请求
     *
     * @param paramsJson
     * @return
     */
    public JSONObject sendPostOKHttpRequest(JSONObject paramsJson, String token) {
        JSONObject resultJson = new JSONObject();
        BaseBean baseBean = new BaseBean();
        String message = "";
        String data = "";
        String baseUrl = Util.null2String(baseBean.getPropValue("zhlxec", "url"));
        String appid = Util.null2String(baseBean.getPropValue("zhlxec", "appid"));
        String userid = Util.null2String(baseBean.getPropValue("zhlxec", "userid"));
        String params = "fromid=" + paramsJson.getString("fromid") + "&toid=" + paramsJson.getString("toid") +
                "&transferType=resource&authorityTag=transfer&submitJson=" +
                "&T122All=1&T122AllNum=" + paramsJson.getString("T122AllNum") +
                "&T131All=1&T131AllNum=" + paramsJson.getString("T131AllNum") +
                "&T133IdStr=" + paramsJson.getString("T133IdStr");
        String apiUrl = baseUrl + "/api/hrm/permissiontoadjust/processData";
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            RequestBody body = RequestBody.create(mediaType, params);
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .addHeader("appid", appid)
                    .addHeader("token", token)
                    .addHeader("userid", userid)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .method("POST", body)
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            if (!"".equals(result)) {
                data = result;
                message = "success";
            } else {
                message = "response result is null";
            }
        } catch (Exception e) {
            message = "response timeout";
            baseBean.writeLog(">>>>>sendOKHttpRequest>>>>>Exception=" + e.getMessage(), e);
        }
        resultJson.put("data", data);
        resultJson.put("message", message);
        return resultJson;
    }

    /**
     * 获取token
     *
     * @return
     */
    public JSONObject getApplytoken() {
        JSONObject resultJson = new JSONObject();
        String message = "";
        String data = "";
        BaseBean baseBean = new BaseBean();
        String baseUrl = Util.null2String(baseBean.getPropValue("zhlxec", "url"));
        String appid = Util.null2String(baseBean.getPropValue("zhlxec", "appid"));
        String secret = Util.null2String(baseBean.getPropValue("zhlxec", "secret"));
        String apiUrl = baseUrl + "/api/ec/dev/auth/applytoken";
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "");
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .addHeader("appid", appid)
                    .addHeader("secret", secret)
                    .method("POST", body)
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            if (!"".equals(result)) {
                data = result;
                message = "success";
            } else {
                message = "response result is null";
            }
        } catch (Exception e) {
            message = "response timeout";
            new BaseBean().writeLog(">>>>>sendOKHttpRequest>>>>>Exception=" + e.getMessage(), e);
        }
        resultJson.put("data", data);
        resultJson.put("message", message);
        return resultJson;
    }

    /**
     * 获取不要转发和抄送的待办多个requestid
     *
     * @return
     */
    public String getRequestidStr(String userid) {
        StringBuilder sb = new StringBuilder();
        RecordSet rs = new RecordSet();
        rs.executeQuery("select t1.requestid from workflow_requestbase t1," +
                "workflow_currentoperator t2,workflow_base t3 where t1.requestid = t2.requestid " +
                "and t1.workflowid=t3.id and t2.userid in (" + userid + ") and t2.usertype=0 " +
                "and (nvl(t1.currentstatus,-1) = -1 or (nvl(t1.currentstatus,-1)=0 and t1.creater in (" + userid + "))) " +
                " and (t1.deleted<>1 or t1.deleted is null or t1.deleted='') " +
                " and ((t2.isremark='0' and (t2.takisremark is null or t2.takisremark=0 ))) " +
                " and t2.islasttimes=1 and (isprocessing = '' or isprocessing is null) " +
                " and t3.isvalid in('1','3')");
        while (rs.next()) {
            String requestid = Util.null2String(rs.getString(1));
            sb.append(requestid).append(",");

        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }


}

